package com.jeewms.www.wms.ui.acitivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.jeewms.www.wms.BR;
import com.jeewms.www.wms.R;
import com.jeewms.www.wms.base.BaseActivity;
import com.jeewms.www.wms.bean.bean.MessageEvent;
import com.jeewms.www.wms.bean.listvm.StockQueryListVm;
import com.jeewms.www.wms.bean.listvm.StorageManagerListVm;
import com.jeewms.www.wms.bean.listvm.StorageMoveListVm;
import com.jeewms.www.wms.bean.vm.CollectGoodsVm;
import com.jeewms.www.wms.bean.vm.PickingSaveVm;
import com.jeewms.www.wms.bean.vm.StorageManagerVm;
import com.jeewms.www.wms.constance.Constance;
import com.jeewms.www.wms.ui.adapter.RecyclerViewBindingAdapter;
import com.jeewms.www.wms.ui.adapter.StorageManagerAdapter;
import com.jeewms.www.wms.ui.adapter.StorageMoveAdapter;
import com.jeewms.www.wms.ui.itemview.StorageManagerItemView;
import com.jeewms.www.wms.util.GsonUtils;
import com.jeewms.www.wms.util.LoadingUtil;
import com.jeewms.www.wms.util.Logutil;
import com.jeewms.www.wms.util.SharedPreferencesUtil;
import com.jeewms.www.wms.util.StringUtil;
import com.jeewms.www.wms.util.ToastUtil;
import com.jeewms.www.wms.util.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.jeewms.www.wms.volley.HTTPUtils;
import com.jeewms.www.wms.volley.VolleyListener;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.SwipeDismissAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 13799 on 2018/6/7.
 * <p>
 * 库位管理
 */

public class StorageManagerActivity extends BaseActivity     {

    RecyclerViewBindingAdapter<StorageManagerVm> adapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_search)
    AutoCompleteTextView etSearch;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.et_search2)
    AutoCompleteTextView etSearch2;
    public static void show(Context context) {
        Intent intent = new Intent(context, StorageManagerActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mBtnLeft.setVisibility(View.VISIBLE);
        setTitle("库位管理");
        addAdapter();


        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int i, KeyEvent keyEvent) {

                if (i == KeyEvent.KEYCODE_ENTER) {
                    getDate(etSearch.getText().toString(),etSearch2.getText().toString());
                    final EditText et_search2 = (EditText) findViewById(R.id.et_search2);
                    et_search2.requestFocus();
                    return true;
                }
                return false;
            }
        });




        etSearch2.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int i, KeyEvent keyEvent) {

                if (i == KeyEvent.KEYCODE_ENTER) {
                    getDate(etSearch.getText().toString(),etSearch2.getText().toString());
                    final EditText et_search2 = (EditText) findViewById(R.id.et_search2);
                    if(!StringUtil.isEmpty(et_search2.getText().toString())){
                        et_search2.setText("");

                    }
                    return true;
                }
                return false;
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_GO){
                    getDate(etSearch.getText().toString(),etSearch2.getText().toString());
                    return true;
                }
                return false;
            }
        });
        getDate("","");
        LoadingUtil.showLoading(this);

    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(MessageEvent msg) {
        getDate(etSearch.getText().toString(),etSearch2.getText().toString());
    }
    private void addAdapter() {


        adapter = new RecyclerViewBindingAdapter(BR.item, R.layout.item_storage_manager) {
            @Override
            public void onBindViewHolder(BindingHolder holder, @SuppressLint("RecyclerView") final int position) {
                super.onBindViewHolder(holder, position);

                holder.itemView.findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                         save(position,adapter.getData().get(position));
                    }
                });
            }
        };
        recyclerView.setAdapter(adapter);




    }





    private void save(final int position, StorageManagerVm vm) {

        if (vm.baseGoodsCount == null || vm.baseGoodsCount.equals("")){
            ToastUtil.show(this , "移动数量不能为空");
            return;
        }
        if (Integer.parseInt(vm.baseGoodsCount) > Integer.parseInt(vm.getGoodsQua())){
            ToastUtil.show(this , "移动数量不能大于原有数量");
            return;
        }

        if (vm.getBinTo()== null|| vm.getBinTo().equals("")){
            ToastUtil.show(this , "移入储位不能为空");
            return;
        }

        LoadingUtil.showLoading(this);
        Map<String, String> map = new HashMap<>();
        map.put("id", vm.getId());
       // map.put("updateBy", SharedPreferencesUtil.getInstance(this).getKeyValue(Constance.SHAREP.LOGINNAME));
        map.put("baseGoodsCount",vm.baseGoodsCount);



        map.put("binFrom",vm.getKuWeiBianMa());
        map.put("tinFrom",vm.getBinId());

        map.put("tinId",vm.getTinId());
        map.put("binTo",vm.getBinTo());
        map.put("goodsId",vm.getGoodsId());
        HTTPUtils.post(this
                , Constance.getStockMoveControllerURL(), map, new VolleyListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LoadingUtil.hideLoading();
                ToastUtil.show(StorageManagerActivity.this, "未知错误");
            }
            @Override
            public void onResponse(String response) {
                Logutil.print("re=="+response);
                LoadingUtil.hideLoading();
                PickingSaveVm vm = GsonUtils.parseJSON(response, PickingSaveVm.class);
                if (vm != null && vm.isOk()) {
                     adapter.remove(position);
                }else if(vm!=null){
                    ToastUtil.show(StorageManagerActivity.this,vm.getErrorMsg());
                }else{
                    ToastUtil.show(StorageManagerActivity.this, "未知错误");
                }
            }
        });
    }


    @Override
    protected int getContentResId() {
        return R.layout.activity_store_manager;
    }


    private void getDate(String searchKey,String searchKey2) {

        Map<String, String> params = new HashMap<>();
        String url = Constance.getStockControllerURL() + "?username=" + SharedPreferencesUtil.getInstance(this).getKeyValue(Constance.SHAREP.LOGINNAME);
        url += "&searchstr=" + searchKey;
        url += "&searchstr2=" + searchKey2;
        HTTPUtils.get(this, url, new VolleyListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

            @Override
            public void onResponse(String response) {
                StorageManagerListVm vm = GsonUtils.parseJSON(response, StorageManagerListVm.class);

                for (StorageManagerVm storageManagerVm : vm.getObj()) {
                    storageManagerVm.baseGoodsCount = storageManagerVm.getGoodsQua();
                }

                adapter.setData(vm.getObj());
                adapter.notifyDataSetChanged();


                LoadingUtil.hideLoading();

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {
        getDate(etSearch.getText().toString(),etSearch2.getText().toString());
    }
}
